package org.frame.auth.service.impl;

import javax.annotation.Resource;

import org.frame.auth.common.exception.CustomException;
import org.frame.auth.common.exception.user.CaptchaException;
import org.frame.auth.common.exception.user.CaptchaExpireException;
import org.frame.auth.common.exception.user.UserPasswordNotMatchException;
import org.frame.auth.service.ILoginService;
import org.frame.auth.token.LoginUser;
import org.frame.auth.token.TokenService;
import org.frame.common.core.constants.Constants;
import org.frame.common.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * 登录 服务实现
 * 
 * @author ruoyi
 */
@Slf4j
@Service
public class LoginServiceImpl implements ILoginService {

	@Autowired
	private TokenService tokenService;
	@Resource
	private AuthenticationManager authenticationManager;
	@Autowired
	private RedisCache redisCache;

	
	@Override
	public String login(String username, String password, String code, String uuid) {
		String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
		String captcha = redisCache.getCacheObject(verifyKey);
		redisCache.deleteObject(verifyKey);
		if (captcha == null) {
			throw new CaptchaExpireException();
		}
		if (!code.equalsIgnoreCase(captcha)) {
			throw new CaptchaException();
		}
		// 用户验证
		Authentication authentication = null;
		try {
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(username, password));
		} catch (Exception e) {
			log.error("登录异常",e);
			if (e instanceof BadCredentialsException) {
				throw new UserPasswordNotMatchException();
			} else {
				throw new CustomException(e.getMessage());
			}
		}
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		// 生成token
		return tokenService.createToken(loginUser.getTokenUser());
	}

}
